package com.wangzeqi.neihanduanzi.home.video;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageButton;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.wangzeqi.neihanduanzi.R;
import com.wangzeqi.neihanduanzi.base.GestureListener;
import com.wangzeqi.neihanduanzi.entity.AllEntity;
import com.wangzeqi.neihanduanzi.entity.DataEntity;
import com.wangzeqi.neihanduanzi.home.video.entity.greendao.DaoMaster;
import com.wangzeqi.neihanduanzi.home.video.entity.greendao.DaoSession;
import com.wangzeqi.neihanduanzi.home.video.entity.greendao.VideoEntity;
import com.wangzeqi.neihanduanzi.home.video.entity.greendao.VideoEntityDao;

import java.util.ArrayList;
import java.util.List;


/**
 * Created by dllo on 16/1/8.
 */
public class FragmentVideo extends Fragment implements View.OnClickListener {

    // 数据库
    private SQLiteDatabase db;
    // 管理者
    private DaoMaster mDaoMaster;
    // 会话
    private DaoSession mDaoSession;
    private Context context;
    private AdapterVideo adapterVideo;
    private RecyclerView recyclerView;
    private AllEntity allEntity;
    private ImageButton button;
    private SwipeRefreshLayout swipeRefreshLayout;
    private RequestQueue queue;
    private String url = "http://ic.snssdk.com/neihan/stream/mix/v1/?content_type=-104";
    VideoEntityDao videoEntityDao;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        this.context = context;
    }
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.video_fragment, null);
        swipeRefreshLayout = (SwipeRefreshLayout) view.findViewById(R.id.refresh_video);
        recyclerView = (RecyclerView) view.findViewById(R.id.rv_video);
        button = (ImageButton) view.findViewById(R.id.btn_video);
        return view;
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        recyclerView.setLongClickable(true);
        recyclerView.setOnTouchListener(new MyGestureListener(context));

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                addVideoData();
                swipeRefreshLayout.setRefreshing(false);

            }
        });
        button.setOnClickListener(this);
        adapterVideo = new AdapterVideo(context);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setAdapter(adapterVideo);
        starAnimation();
        addVideoData();
        // 此DevOpenHelper类继承自SQLiteOpenHelper,第一个参数Context,第二个参数数据库名字,第三个参数CursorFactory
        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(context, "videodao.db", null);
        db = helper.getWritableDatabase();
        mDaoMaster = new DaoMaster(db);
        mDaoSession = mDaoMaster.newSession();
        videoEntityDao = mDaoSession.getVideoEntityDao();
    }


    private void addVideoData() {
        queue = Volley.newRequestQueue(context);
        StringRequest request = new StringRequest(url, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                allEntity = gson.fromJson(response, AllEntity.class);
                adapterVideo.addData(allEntity);
                stopAnimation();
                Toast.makeText(context, "刷新完成", Toast.LENGTH_SHORT).show();

            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                stopAnimation();
                Toast.makeText(context, "网络错误", Toast.LENGTH_SHORT).show();
            }
        });
        queue.add(request);
    }


    @Override
    public void onClick(View v) {
        starAnimation();
        addVideoData();
        recyclerView.scrollToPosition(0);

    }

    private void starAnimation() {
        /** 设置旋转动画 */
        final RotateAnimation animation = new RotateAnimation(0f, 359f, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        button.setAnimation(animation);
        animation.setDuration(500);//设置动画持续时间
        animation.setRepeatCount(1000);
        /** 开始动画 */
        animation.startNow();
    }

    private void stopAnimation() {
        /** 设置旋转动画 */
        final RotateAnimation animation = new RotateAnimation(0f, 359f, Animation.RELATIVE_TO_SELF,
                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
        animation.setDuration(500);//设置动画持续时间
        animation.setRepeatCount(1000);
        button.setAnimation(animation);
        /** 结束动画 */
        animation.cancel();
    }


    private class MyGestureListener extends GestureListener {
        public MyGestureListener(Context context) {
            super(context);
        }

        @Override
        public boolean up() {
            recyclerView.bringToFront();
            return super.up();
        }

        @Override
        public boolean down() {
            button.bringToFront();
            return super.down();
        }
    }
    private void initDatabase() {

        // 对数据库内的表进行操作
        List<VideoEntity> dataList = new ArrayList<>();
        for (int i = 0; i < adapterVideo.getItemCount(); i++) {
            DataEntity entity = allEntity.getData().getData().get(i);
            String content = entity.getGroup().getContent();
            String comment_conut = entity.getGroup().getComment_count();
            String share_count = entity.getGroup().getShare_count();
            String bury_count = entity.getGroup().getBury_count();
            String digg_count = entity.getGroup().getDigg_count();
            String category_name = entity.getGroup().getCategory_name();
            String text = entity.getGroup().getText();
            String name = entity.getGroup().getUser().getName();
            if (entity.getGroup() != null && entity.getComments().size() > 0) {
                String user_name = entity.getComments().get(0).getUser_name();
                String comment_text = entity.getComments().get(0).getText();
                int comment_digg_count = entity.getComments().get(0).getDigg_count();
                VideoEntity data = new VideoEntity((long) i, content, comment_conut, share_count, bury_count, digg_count, category_name,
                        text, name, user_name, comment_text, comment_digg_count);
               videoEntityDao.insert(data);
            } else if (entity.getGroup() != null) {
                VideoEntity data = new VideoEntity((long) i, content, comment_conut, share_count, bury_count, digg_count, category_name,
                        text, name, null, null, null);
                videoEntityDao.insert(data);
            }
        }
    }

    private void getData(){

    }
}
